package game.module.nn.processor;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.nn.bean.NnQiangZhuangJiaInfo;
import game.module.nn.bean.NnRound;
import game.module.nn.logic.NnDataManager;
import game.session.SessionManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageNn.C2SNnQiangZhuangJia;
import lua.LuaMessageNn.PushNnQiangZhuangJia;
import lua.LuaMessageNn.PushNnZhuangJiaSelect;
import lua.LuaMessageNn.S2CNnQiangZhuangJia;

@MsgCodeAnn(msgcode = C2SNnQiangZhuangJia.id, accessLimit = 500)
public class NnQiangZhuangJiaProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(NnQiangZhuangJiaProcessor.class);

	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw request) throws Exception {
		C2SNnQiangZhuangJia reqMsg = C2SNnQiangZhuangJia.parse(request);
		short call_id = reqMsg.call_id;
		int playerId = playingRole.getId();
		logger.info("nn qiang zhuang jia,playerId={},call_id={}", playerId, call_id);
		// 房间是否存在
		NnRound ddzRound = NnDataManager.getInstance().getNnRoom(playerId);
		if (ddzRound == null) {
			S2ErrorCode respMsg = new S2ErrorCode(201);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		int myIndex = ddzRound.getPlayerIds().indexOf(playerId);
		// 分数是否比之前的大
		if (ddzRound.getLastJiaoScore() != null && call_id > 0) {
			short lastScore = ddzRound.getLastJiaoScore();
			if (call_id < lastScore) {
				S2ErrorCode respMsg = new S2ErrorCode(304);
				playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
				return;
			}
		}
		// save
		List<NnQiangZhuangJiaInfo> qiangZhuangJiaList = ddzRound.getQiangZhuangJiaInfoList();
		if (qiangZhuangJiaList == null) {
			qiangZhuangJiaList = new ArrayList<>();
			ddzRound.setQiangZhuangJiaInfoList(qiangZhuangJiaList);
		}
		qiangZhuangJiaList.add(new NnQiangZhuangJiaInfo(myIndex, call_id));
		// 我叫的分数
		int newLoopCount = ddzRound.getLoopCount() + 1;
		logger.info("抢庄家次数={}", newLoopCount);
		// push
		PushNnQiangZhuangJia pushJiaoDiZhu = new PushNnQiangZhuangJia((short) myIndex, call_id);
		List<Integer> playerIds = ddzRound.getPlayerIds();
		for (Integer aPlayerId : playerIds) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushJiaoDiZhu.build(pr.alloc()));
			}
		}
		if (newLoopCount >= ddzRound.getPlayerIds().size()) {
			// 没人叫，随机一个地主
			selectZhuangJia(ddzRound);
		} else {
			ddzRound.setLoopCount(newLoopCount);
			ddzRound.setLastJiaoScore(call_id);
		}
		S2CNnQiangZhuangJia respMsg = new S2CNnQiangZhuangJia();
		playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
	}

	private void selectZhuangJia(NnRound ddzRound) {
		List<NnQiangZhuangJiaInfo> qiangZhuangJiaList = ddzRound.getQiangZhuangJiaInfoList();
		qiangZhuangJiaList.sort(new Comparator<NnQiangZhuangJiaInfo>() {
			@Override
			public int compare(NnQiangZhuangJiaInfo o1, NnQiangZhuangJiaInfo o2) {
				if (o1.getCallRate() > o2.getCallRate()) {
					return -1;
				} else if (o1.getCallRate() < o2.getCallRate()) {
					return 1;
				} else {
					return 0;
				}
			}
		});
		short maxCallRate = qiangZhuangJiaList.get(0).getCallRate();
		int searchEnd = 0;
		for (int i = 1; i < qiangZhuangJiaList.size(); i++) {
			int aCallRate = qiangZhuangJiaList.get(i).getCallRate();
			if (aCallRate < maxCallRate) {
				break;
			} else {
				searchEnd++;
			}
		}
		int randIndex = RandomUtils.nextInt(0, searchEnd + 1);
		NnQiangZhuangJiaInfo zhuangJiaInfo = qiangZhuangJiaList.get(randIndex);
		int myIndex = zhuangJiaInfo.getPlayerIndex();
		short zhuangJiaRate = zhuangJiaInfo.getCallRate();
		// 没人选庄家，分数1
		zhuangJiaRate = zhuangJiaRate > 0 ? zhuangJiaRate : 1;
		ddzRound.setZhuangJiaIndex(myIndex);
		ddzRound.setZhuangJiaRate(zhuangJiaRate);
		// 推送消息
		PushNnZhuangJiaSelect pushDiZhuSelect = new PushNnZhuangJiaSelect((short) myIndex);
		List<Integer> playerIds = ddzRound.getPlayerIds();
		for (Integer aPlayerId : playerIds) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushDiZhuSelect.build(pr.alloc()));
			}
		}
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

}
